package scenic.toolkit;

import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;

import scenic.Graphics;
import scenic.toolkit.event.MouseEvent;
import scenic.toolkit.event.MouseListener;
import scenic.toolkit.event.MouseMotionListener;
import scenic.toolkit.event.MouseWheelEvent;

public class CScrollPane extends CComponent {
	private class EventHandler implements MouseListener, MouseMotionListener {
		public void mouseClicked(MouseEvent event) {
		}

		public void mouseEntered(MouseEvent event) {
		}

		public void mouseExited(MouseEvent event) {
		}

		public void mousePressed(MouseEvent event) {
		}

		public void mouseReleased(MouseEvent event) {
		}

		public void mouseWheelMoved(MouseWheelEvent event) {
			vbar.setPosition(vbar.getPosition() + event.getDeltaY());
		}

		public void mouseDragged(MouseEvent event) {
		}

		public void mouseMoved(MouseEvent event) {
		}		
	}
	
	private CComponent content;
	private CScrollbar hbar = new CScrollbar(CScrollbar.HORIZONTAL);
	private CScrollbar vbar = new CScrollbar(CScrollbar.VERTICAL);

	public CScrollPane(CComponent content) {
		EventHandler eventHandler = new EventHandler();
		
		addMouseListener(eventHandler);
		addMouseMotionListener(eventHandler);
		
		setContent(content);
		addChild(hbar);
		addChild(vbar);
	}
	
	public void setContent(CComponent content) {
		removeChild(this.content);
		this.content = content;
		addChild(this.content);
	}
	
	public void paint(Graphics g) {
		double w = getWidth();
		double h = getHeight();
		double sw = vbar.getMinimumSize().getX();
		double sh = hbar.getMinimumSize().getY();
		double clientWidth = w - sw;
		double clientHeight = h - sh;
		Point2D contentSize = content.getMinimumSizeFor(clientWidth, clientHeight);
		
//		System.out.println("sx: " + contentSize.getX() + " sy: " + contentSize.getY());
		
		hbar.setPosition(0, h - sh, w - sw, sh);
		hbar.setContentSize(contentSize.getX());
		hbar.setViewSize(clientWidth);
		vbar.setPosition(w - sw, 0, sw, h);
		vbar.setContentSize(contentSize.getY());
		vbar.setViewSize(clientHeight);
		
		g.clear();
		g.add(hbar.getScene());		
		g.add(vbar.getScene());
		if(content != null) {
			Point2D p = alignToPixels(new Point2D.Double(-hbar.getPosition(), -vbar.getPosition()), null);
			
			content.setTransform(AffineTransform.getTranslateInstance(p.getX(), p.getY()));
			content.setSize(clientWidth, clientHeight);
			g.rectangle(0, 0, clientWidth, clientHeight);
			g.clip();
			g.add(content.getScene());
		}
	}
}
